package com.be.beadmin.system.cronJob;

import com.be.beadmin.material.entity.PurchaseOrder;
import com.be.beadmin.material.mapper.PurchaseOrderMapper;
import com.be.beadmin.material.repository.PurchaseOrderRepository;
import com.be.beadmin.material.service.PurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author: Mengyang Zhu
 * @Date: 2023/4/17 13:12
 * @Description: updatePurchaseAlerts
 */
@Component
public class updatePurchaseAlerts {

    @Autowired
    private PurchaseOrderRepository purchaseOrderRepository;

    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Scheduled(initialDelay = 5000, fixedRate = 24 * 60 * 60 * 1000) // 任务启动后5秒钟第一次执行，然后每天凌晨1点更新数据库
    public void updateDatabase() {
        List<PurchaseOrder> all = purchaseOrderRepository.findAll();
        //计算每个订单的的预警状态

        for (int i = 0; i < all.size(); i++) {
            PurchaseOrder p = all.get(i);
            //如果全部到货，则不再更新
            if(Objects.equals(p.getIsClosed(), "Y")){
                continue;
            }
            if(p.getDeliveryDate()==null||p.getKickoffDate()==null){
                continue;
            }
            Date date = new Date();
            LocalDate deliveryDate = p.getDeliveryDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate  curTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            long diff = ChronoUnit.DAYS.between(curTime,deliveryDate);

            System.out.print("diff============================");
            System.out.println(diff);

            if (diff>=7){
                //绿色
                p.setPurchaseAlerts("g");
            }else if(diff>=3){
                //黄色
                p.setPurchaseAlerts("y");
            }else{
                //红色
                p.setPurchaseAlerts("r");
            }

            if(p.getDeliveryDate().compareTo(p.getSendDate())>0){
                p.setIsShort("1");
            }
            if(p.getKickoffDate()==null){
                p.setIsShort("1");
            }
            purchaseOrderRepository.save(p);
        }
    }
}
